package shiro.authc.sys.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shiro.authc.common.JsonResult;

/**
 * @author 李岩峰
 * @date 2017/11/21 16:37
 * @description
 */
@Controller
@RequestMapping("/sys")
public class SysController
{

	@RequestMapping("/to_login")
	public String toLoginUI()
	{
		return "/admin/login";
	}

	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public JsonResult submitLogin(String username, String password)
	{
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);

		try
		{
			subject.login(token);
		}
		catch (AuthenticationException e)
		{
			String simpleName = e.getClass().getSimpleName();
			if ("UnknownAccountException".equals(simpleName))
			{
				return JsonResult.failure("用户名不正确");
			}
			else if ("IncorrectCredentialsException".equals(simpleName))
			{
				return JsonResult.failure("密码不正确");
			}
		}
		boolean authenticated = subject.isAuthenticated();
		if (authenticated)
		{
			return JsonResult.success("/sys/index");
		}
		return JsonResult.failure("请检查用户信息");
	}

	@RequestMapping("/index")
	public String toIndex()
	{
		return "/admin/index";
	}
}
